import pymysql

class MySQL():

    def __init__(self,host,user,pwd,dbName):
        self.host = host
        self.user = user
        self.pwd = pwd
        self.dbName = dbName

    def connect(self):
        self.db = pymysql.connect(self.host,self.user,self.pwd,self.dbName,use_unicode=True)

        self.cursor = self.db.cursor()

    #关闭数据库
    def close(self):
        self.cursor.close()
        self.db.close()

    #单条数据的查询
    def get_one(self,sql):
        try:
            self.connect()
            self.cursor.execute(sql)
            res = self.cursor.fetchone()
            self.close()
        except Exception:
            res = None
        return res


    def get_all(self,sql):
        try:
            self.connect()
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
            self.close()
            return res
        except Exception as e:
            raise e
    
    def insert(self,sql):
        return self.__edit(sql)

    def update(self,sql):
        return self.__edit(sql)

    def delete(self,sql):
        return self.__edit(sql)

    def __edit(self,sql):
        try:
            self.connect()
            count = self.cursor.execute(sql)
            self.db.commit()
            self.close()
        except:
            self.db.rollback()
            count = 0
        return count
host = "172.17.0.2"
user = "root"
dbName = "test"
pwd = "123.com"
mysql = MySQL(host,user,pwd,dbName)
sql = "select name,age from user"
res = mysql.get_all(sql)
for row in res:
    print(row)
